﻿using Hjt212Parser;
using HPSocketCS;
using log4net;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HpSocketIotGateway.Facade
{
    /// <summary>
    /// 缓存类，缓存信息、客户端连接
    /// </summary>
    public class BufferFacade
    {
        private static Dictionary<string, DateTime> _lastMn = new Dictionary<string, DateTime>();

        private static DateTime now;
        private static DateTime lasTime;

        public static bool IsSameToLastMn(string mn)
        {
            try
            {
                now = DateTime.Now;
                if (_lastMn.ContainsKey(mn))
                {
                    _lastMn.TryGetValue(mn, out lasTime);
                    _lastMn.Remove(mn);
                    if (lasTime != null && Math.Abs((now - lasTime).TotalSeconds) < 3)
                    {
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            finally
            {
                if (_lastMn.Count > 10000 && MyTimer.IsToTheTime("BufferFacade.IsSameToLastMn", 240))
                {
                    _lastMn.Clear();
                }

                _lastMn.Add(mn, now);
            }
            return false;
        }
        //private static readonly Queue<string> Queue = new Queue<string>();
        private static readonly ILog Log = LogManager.GetLogger(typeof(BufferFacade));
        /// <summary>
        /// 接收服务器
        /// </summary>
        public static readonly TcpServer Server = new TcpServer();
        /// <summary>
        /// 消息队列-原始消息、持久化消息、响应消息、实时数据消息、非实时数据消息
        /// </summary>
        private static readonly ConcurrentQueue<string> Queue4Persistence = new ConcurrentQueue<string>();

        private static readonly ConcurrentQueue<string> Queue4Persistence4GatewayResponse = new ConcurrentQueue<string>();
        /// <summary>
        ///  客户端缓存
        /// </summary>
        private static readonly ConcurrentDictionary<IntPtr, string> SocketClientBuffer = new ConcurrentDictionary<IntPtr, string>();

        public static int QueueCount()
        {
            return Queue4Persistence.Count;
        }

        public static int QueueCount4GatewayResponse()
        {
            return Queue4Persistence4GatewayResponse.Count;
        }
        /// <summary>
        /// 根据持久化还是业务处理添加消息到相应的消息队列
        /// </summary>
        /// <param name="msg">消息</param>
        public static void EnqueueToMessageQueue(string msg)
        {
            if (Queue4Persistence.Count <= 500000)
            {
                Queue4Persistence.Enqueue(msg);
            }
        }

        public static void EnqueueToMessageQueue4GatewayResponse(string msg)
        {
            if (Queue4Persistence4GatewayResponse.Count <= 500000)
            {
                Queue4Persistence4GatewayResponse.Enqueue(msg);
            }
        }
        /// <summary>
        /// 根据持久化还是业务处理从相应的消息队列获得消息
        /// </summary>
        public static string DequeueFromMessageQueue()
        {
            Queue4Persistence.TryDequeue(out var result);
            return result;
        }

        public static string DequeueFromMessageQueue4GatewayResponse()
        {
            Queue4Persistence4GatewayResponse.TryDequeue(out var result);
            return result;
        }
        /// <summary>
        /// 添加客户端连接Socket到缓冲
        /// </summary>
        /// <param name="connId"></param>
        /// <param name="mn"></param>
        public static void AddSocketClient(IntPtr connId, string mn)
        {
            try
            {
                if (!SocketClientBuffer.ContainsKey(connId))
                {
                    SocketClientBuffer.TryAdd(connId, mn);
                    Info();
                }
                else
                {
                    SocketClientBuffer.TryGetValue(connId, out var oldMn);
                    if (!mn.Equals(oldMn))
                    {
                        SocketClientBuffer.TryRemove(connId, out oldMn);
                        SocketClientBuffer.TryAdd(connId, mn);
                        Log.Warn(connId + " Corresponding MN inconsistencies:" + oldMn + "!=" + mn);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
        /// <summary>
        /// 从缓冲区移除无效客户端连接
        /// </summary>
        /// <param name="connId"></param>
        /// <returns></returns>
        public static string RemoveSocketClient(IntPtr connId)
        {
            string mn = null;
            try
            {
                SocketClientBuffer.TryRemove(connId, out mn);
                Info();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            return mn;
        }
        /// <summary>
        /// 根据mn号获取客户端Socket连接
        /// </summary>
        /// <param name="mn"></param>
        /// <returns></returns>
        private static List<IntPtr> GetSocketClient(string mn)
        {
            List<IntPtr> list = new List<IntPtr>();
            try
            {
                var items = SocketClientBuffer.Where(t => t.Value == mn);
                list.AddRange(items.Select(item => item.Key));
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            return list;
        }
        /// <summary>
        /// 发送消息到指定的MN对应Socket，如果MN没有，找对应表的IP对应的Socket
        /// </summary>
        /// <param name="mn"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SendMsgToClientOri(string mn, string msg)
        {
            try
            {
                //Log.Info("Prepare downline message:" + msg);
                if (string.IsNullOrEmpty(mn))
                {
                    return false;
                }

                var clients = GetSocketClient(mn);
                if (clients == null || clients.Count < 1)
                {
                    var feature = GetIpByMn(mn);
                    if (string.IsNullOrEmpty(feature))
                    {
                        Log.Info(mn + " is offine 1:Not downline message:" + msg);
                        return false;
                    }
                    clients = GetSocketClient(feature);
                }

                if (clients == null || clients.Count < 1)
                {
                    Log.Info(mn + " is offine 2:Not downline message:" + msg);
                    return false;
                }
                if (BufferFacade.IsSameToLastMn(mn))
                {
                    ThreadUtil.Sleep(3000);
                }
                foreach (IntPtr client in clients)
                {
                    SendMsgToClient(client, msg);
                }
                Log.Info("Downline message successfully:" + msg);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            Log.Info("Downline message failure:" + msg);
            return false;
        }


        public static bool SendMsgToClient(string mn, string msg)
        {
            bool flag = true;
            try
            {
                //Log.Info("Prepare downline message:" + msg);
                if (string.IsNullOrEmpty(mn))
                {
                    flag = false;
                }
                if (flag)
                {
                    var clients = GetSocketClient(mn);
                    if (clients == null || clients.Count < 1)
                    {
                        flag = false;
                    }
                    if (flag)
                    {
                        foreach (IntPtr client in clients)
                        {
                            SendMsgToClient(client, msg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                flag = false;
                Log.Error(ex);
            }
            if (!flag)
            {
                Log.Info("Downline message failure     :" + msg);
            }
            else
            {
                Log.Info("Downline message successfully:" + msg);
            }
            return flag;
        }

        private static void SendMsgToClient(IntPtr client, string msg)
        {
            //不再提供Crc拼装
            if (string.IsNullOrEmpty(Parser.GetStringByKey("Length", msg)))
            {
                msg = Crc.WrapByCrc(msg, "Monitor");
            }
            if (string.IsNullOrEmpty(msg))
            {
                return;
            }

            var items = msg.Split(new[] { "%&%" }, StringSplitOptions.RemoveEmptyEntries);
            bool isNeedSleep = items.Length > 1;
            foreach (var item in items)
            {
                if (string.IsNullOrEmpty(item))
                {
                    continue;
                }

                byte[] sendBytes = null;
                if (item.Contains("\n"))
                {
                    sendBytes = Encoding.Default.GetBytes(item );
                }
                else
                {
                    sendBytes = Encoding.Default.GetBytes(item + "\n");
                }
                Server.Send(client, sendBytes, sendBytes.Length);
                if (isNeedSleep)
                {
                    ThreadUtil.Sleep(2000);
                }
            }

        }
        public static List<string> GetMNs()
        {
            try
            {
                return SocketClientBuffer.Select(t => t.Value).ToList();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            return null;
        }

        private static void Info()
        {
            try
            {
                List<string> list = GetMNs();
                Log.Info("Socket information:" + list.Distinct().Count() + "/" + list.Count + "/" + Server.ConnectionCount);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        // private static List<controller> _controllers;

        private static string GetIpByMn(string mn)
        {
            //try
            //{
            //    if (MyTimer.IsToTheTime("BufferFacade.GetIpByMn", 10))
            //    {
            //        using (var ctx = new GatewayContext())
            //        {
            //            _controllers = ctx.controllers.AsNoTracking().ToList();
            //        }
            //    }
            //    if (_controllers != null && _controllers.Count > 0)
            //    { return _controllers.FirstOrDefault(t => t.mn.Equals(mn))?.feature; }
            //}
            //catch (Exception ex)
            //{
            //    Log.Error(ex);
            //}
            return null;
        }
    }


}
